package com.ray.finance.strategy.bill.create;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ray.business.check.BusinessCheck;
import com.ray.business.enums.BusinessTypeEnum;
import com.ray.business.service.ProdBusinessDeductionService;
import com.ray.business.service.ProdBusinessService;
import com.ray.business.table.entity.ProdBusiness;
import com.ray.business.table.entity.ProdBusinessDeduction;
import com.ray.finance.builder.BillBuilder;
import com.ray.finance.enums.BillSourceEnum;
import com.ray.finance.enums.BillStatusEnum;
import com.ray.finance.enums.BillTypeEnum;
import com.ray.finance.service.FinaBillService;
import com.ray.finance.table.entity.FinaBill;
import com.ray.finance.table.params.bill.BillCreateParams;
import com.ray.magicBlock.Strategy;
import com.ray.magicBlock.anno.Block;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author bo shen
 * @Description: 对账单
 * @Class: PurchaseInService
 * @Package com.ray.wms.strategy.in
 * @date 2020/6/8 15:05
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Block(group = "createBill", strategy = "BUSINESS", desc = "加工对账单")
public class BusinessCreateService implements Strategy<BillCreateParams, LoginUser, String> {

    @Autowired
    private ProdBusinessService prodBusinessService;
    @Autowired
    private ProdBusinessDeductionService prodBusinessDeductionService;
    @Autowired
    private FinaBillService finaBillService;

    @Override
    public String execute(BillCreateParams createParams, LoginUser loginUser) {
        //查询加工单列表
        List<String> orderNos = createParams.getOrderNos();
        List<ProdBusiness> businessList = prodBusinessService.listByOrderNos(createParams.getOrderNos(), BusinessTypeEnum.IN.getValue(), loginUser);
        if (ObjectUtil.isEmpty(businessList) || businessList.size() != orderNos.size()) {
            log.info("查询到的加工单数量与订单接口数量不一致,参数：{},结果:{}", orderNos.size(), businessList.size());
            throw BusinessExceptionFactory.newException("加工单数量与订单接口数量不一致");
        }
        //客户数据
        String customerCode = null;
        //步骤数据
        String stepCode = null;
        //总金额
        BigDecimal total = new BigDecimal(0);
        for (ProdBusiness prodBusiness : businessList) {
            if (StrUtil.isBlank(customerCode)) {
                customerCode = prodBusiness.getCustomerCode();
                stepCode = prodBusiness.getStepCode();
            }
            new BusinessCheck(prodBusiness).checkNull("").canBill(String.format("订单[%s]不能对账", prodBusiness.getBusinessCode()));
            if (!StrUtil.equals(customerCode, prodBusiness.getCustomerCode()) || !StrUtil.equals(stepCode, prodBusiness.getStepCode())) {
                log.info("客户或加工节点不一致");
                throw BusinessExceptionFactory.newException("客户或加工节点不一致");
            }
            total = total.add(NumberUtil.null2Zero(prodBusiness.getPrice()).multiply(prodBusiness.getQuantity()));
        }
        //查询扣款金额
        List<ProdBusinessDeduction> prodBusinessDeductions = prodBusinessDeductionService.listByOrderNos(orderNos, loginUser);


        BigDecimal deduction = new BigDecimal(0);
        if (ObjectUtil.isNotEmpty(prodBusinessDeductions)) {
            deduction = prodBusinessDeductions.stream().map(ProdBusinessDeduction::getAmount).reduce(BigDecimal::add).get();
        }
        BillBuilder billBuilder = new BillBuilder();
        billBuilder.appendCreate(loginUser).appendOrderStatus(BillStatusEnum.UN_CHECK.getValue());
        FinaBill finaBill = billBuilder.bulid();
        finaBill.setTotalAmount(total);
        finaBill.setDeductionAmount(deduction);
        finaBill.setAmount(total.subtract(deduction));
        finaBill.setCustomerCode(customerCode);
        finaBill.setStepCode(stepCode);
        finaBill.setCurrency("人民币");//加工单默认人民币结算
        finaBill.setBillType(BillTypeEnum.OUT.getValue());
        finaBill.setBillSource(BillSourceEnum.BUSINESS.getValue());
        //保存
        finaBillService.save(finaBill);
        //保存关联
        if (!prodBusinessService.comfireBill(orderNos, billBuilder.getCode(), loginUser)) {
            log.info("更新加工单对账信息异常:{},对账单:{}", orderNos, billBuilder.getCode());
            throw BusinessExceptionFactory.newException("更新加工单对账信息异常");
        }
        //判断是否存在扣款单
        if (prodBusinessDeductionService.countBill(orderNos, loginUser) > 0) {
            if (!prodBusinessDeductionService.comfireBill(orderNos, billBuilder.getCode(), loginUser)) {
                log.info("更新加工单扣款对账信息异常:{},对账单:{}", orderNos, billBuilder.getCode());
                throw BusinessExceptionFactory.newException("更新加工单扣款对账信息异常");
            }
        }
        return billBuilder.getCode();
    }
}
